﻿using System;
using NodeEditorFramework;
using UnityEditor;
using UnityEngine;
using MainScene.Evt.Condition;
using MainScene.Evt.Command;
using MainScene;

public sealed class DataEditorGUIColor : IDisposable
{
    private Color _prevGUIColor;
    private Color _prevHandleColor;

    public DataEditorGUIColor(Color color)
    {
        _prevGUIColor = GUI.color;
        _prevHandleColor = Handles.color;

        GUI.color = color;
      //  Handles.color = color; 
    }

    public void Dispose()
    {
       // Handles.color = _prevHandleColor;
        GUI.color = _prevGUIColor;
    }
}
/// <summary>
/// This node has one entry and one exit, it is just to display something, then move on
/// </summary>
[Node(false, "LevelMap/Story Node", new Type[] { typeof(LevelMapNodeCanvas) })]
public class StoryNode : BaseStoryNode
{
    public override string Title { get { return events !=null ?  events.eventId:  "Story Node"; } }
    public override Vector2 MinSize { get { return new Vector2(350, 60); } }
    public override bool AutoLayout { get { return true; } }

    private const string Id = "StoryNode";
    public override string GetID { get { return Id; } }
    public override Type GetObjectType { get { return typeof(StoryNode); } }

    //Previous Node Connections
    [ValueConnectionKnob("From Previous", Direction.In, "StoryForward", NodeSide.Left, 30)]
    public ValueConnectionKnob fromPreviousIN;
    [ConnectionKnob("To Previous", Direction.Out, "StoryBack", NodeSide.Left, 50)]
    public ConnectionKnob toPreviousOut;

    //Next Node to go to
    [ValueConnectionKnob("To Next", Direction.Out, "StoryForward", NodeSide.Right, 30)]
    public ValueConnectionKnob toNextOUT;
    [ConnectionKnob("From Next", Direction.In, "StoryBack", NodeSide.Right, 50)]
    public ConnectionKnob fromNextIN;

    #region 添加条件 和 操作
    public void ResetOption()
    {
        ResetCommond();
        ResetCondtion();
    }
    private void ResetCommond()
    {
        isEditorNewCell = false;
        EditorCommandIndex = -1;
        new_story_command = null;
    }
    private void ResetCondtion()
    {
        isEditorNewCondition = false;
        EditorConditonIndex = -1;
        new_story_condtion = null;
    }

    public bool NeedDrawSubPanel()
    {
        return isEditorNewCell || isEditorNewCondition || EditorConditonIndex != -1 || EditorCommandIndex != -1;
    }
    /// <summary>
    /// 是否添加新的命令
    /// </summary>
    public bool isEditorNewCell = false;
    /// <summary>
    /// 是否添加新的条件
    /// </summary>
    public bool isEditorNewCondition = false;
    /// <summary>
    /// 当前操作选中的条件
    /// </summary>
    public int EditorConditonIndex = -1;
    /// <summary>
    /// 当前操作选中的命令
    /// </summary>
    public int EditorCommandIndex = -1;

    public ConditionData new_story_condtion = null;//新加的条件
    public EvtCommandType new_command_type = EvtCommandType.ActionCommand;

    public CommandData new_story_command = null; //新加的命令
    public EvtConditionType new_condition_type = EvtConditionType.OnAction;

    public CommandData GetCell(int idx)
    {
        return events.m_content_data_list[idx];
    }
    public ConditionData GetCondition(int idx)
    {
        return events.m_condition_data_list[idx];
    }
    public void AddNewCommand(CommandData newData)
    {
        events.m_content_data_list.Add(newData);
    }
    public void AddNewCondtion(ConditionData newData)
    {
        events.m_condition_data_list.Add(newData);
    }
    #endregion

    #region NodeGUI
    private bool isOptionDownFlag= false;
    private bool isConditionDownFlag = true;
    private GUILayoutOption dynamicHeightNor = GUILayout.Height(25);
    private GUILayoutOption dynamicHeight = GUILayout.Height(25);
    private GUILayoutOption dynamicHeight200 = GUILayout.Height(200);
    private GUILayoutOption dynamicHeight100 = GUILayout.Height(100);
    Vector2 cell_list_scroll_pos = Vector2.zero;
    Vector2 condition_list_scroll_pos = Vector2.zero;
    private Color preColor;
    public override void NodeGUI()
    {
        if (events == null)
        {
            GUILayout.Label("null");
            return;
        }
       
        GUILayout.BeginVertical();
        {
            GUILayout.BeginHorizontal();
            {
                GUILayout.Label("EvnetID:");
                events.eventId = GUILayout.TextField(events.eventId);
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(5);

            GUILayout.BeginHorizontal();
            {
               // GUI.backgroundColor = Color.white;
                events.uiVisible = GUILayout.Toggle(events.uiVisible, "uiVisible");
                events.endForceShowUI = GUILayout.Toggle(events.endForceShowUI, "endShowUI");
                events.disableMainRole = GUILayout.Toggle(events.disableMainRole, "staticPlayer");
                events.storyForever = GUILayout.Toggle(events.storyForever, "awaysExist");
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(5);

            dynamicHeight = isOptionDownFlag ? dynamicHeight200 : dynamicHeightNor;
            GUILayout.BeginVertical(dynamicHeight);
            {
                GUILayout.BeginHorizontal();
                {
                    if (GUILayout.Button(isOptionDownFlag ? "操作 ▼" : "操作 ▲", LevelMapSubEditor.ButtonWidth))
                    {
                        isOptionDownFlag = !isOptionDownFlag;
                    }
                    if (events.m_content_data_list.Count > 0)
                    {
                        preColor = GUI.color;
                        GUI.color = Color.yellow;
                        GUILayout.Label("...");
                        GUI.color = preColor;
                    }
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button("Add New"))
                    {
                        isEditorNewCell = true;
                        isOptionDownFlag = true;
                        ResetCondtion();
                    }
                }
                GUILayout.EndHorizontal();
                if (isOptionDownFlag)
                {
                    DrawCellList();
                }
            }
            GUILayout.EndVertical();

            dynamicHeight = isConditionDownFlag ? dynamicHeight100 : dynamicHeightNor;
            GUILayout.BeginVertical(dynamicHeight);
            {
                GUILayout.BeginHorizontal();
                if (GUILayout.Button(isConditionDownFlag ? "条件 ▼" : "条件 ▲", LevelMapSubEditor.ButtonWidth))
                {
                    isConditionDownFlag = !isConditionDownFlag;
                }
                if (events.m_condition_data_list.Count > 0)
                {
                    preColor = GUI.color;
                    GUI.color = Color.yellow;
                    GUILayout.Label("...");
                    GUI.color = preColor;
                }
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Add New"))
                {
                    isEditorNewCondition = true;
                    isConditionDownFlag = true;
                    ResetCommond();
                }
                GUILayout.EndHorizontal();
                if (isConditionDownFlag)
                {
                    DrawConditionList();
                }
            }
            GUILayout.EndVertical();
        }
        GUILayout.EndVertical();
    }

  
    private void DrawCellList()
    {
        //绘制列表
        cell_list_scroll_pos = GUILayout.BeginScrollView(cell_list_scroll_pos, "box");
        for (int idx = 0; idx < events.m_content_data_list.Count; ++idx)
        {
            //绘制一行数据
            DrawStoryCell(idx);
        }

        GUILayout.EndScrollView();
    }
    private void DrawStoryCell(int idx)
    {
        var storyCell = events.m_content_data_list[idx];
        if (storyCell == null)
        {
            Debug.LogError(string.Format("EventCell:{0} , Index:{1}  null!",GetEventId,idx));
            return;
        }
        GUILayout.BeginHorizontal(LevelMapSubEditor.ListCellWidth);
        if (GUILayout.Button(EditorCommandIndex == idx ? "Close" : "Editor", LevelMapSubEditor.ButtonWidth))
        {
            EditorCommandIndex = EditorCommandIndex == idx ? -1 : idx;
            ResetCondtion();
        }
        if (GUILayout.Button("Del", LevelMapSubEditor.ButtonWidth))
        {
            EditorCommandIndex = -1;
            events.m_content_data_list.RemoveAt(idx);
        }
        GUILayout.Label(LevelMapSubEditor.DataToString(storyCell.GetType(), storyCell));
        GUILayout.EndHorizontal();
    }
  
    private void DrawConditionList()
    {
        //绘制列表
        condition_list_scroll_pos = GUILayout.BeginScrollView(condition_list_scroll_pos, "box");
        for (int idx = 0; idx < events.m_condition_data_list.Count; ++idx)
        {
            //绘制一行数据
            DrawStoryCondition(idx);
        }

        GUILayout.EndScrollView();
    }
    private void DrawStoryCondition(int idx)
    {
        var storyCondition = events.m_condition_data_list[idx];
        if (storyCondition == null)
        {
            Debug.LogError(string.Format("EventCondition:{0} , Index:{1}  null!", GetEventId, idx));
            return;
        }

        var cyanColor = storyCondition.conditionType == EvtConditionType.OnSceneEvt;
        if (cyanColor)
        {
            preColor = GUI.color;
            GUI.color = Color.cyan;
        }
        GUILayout.BeginHorizontal(LevelMapSubEditor.ListCellWidth);
        if (GUILayout.Button(EditorConditonIndex == idx ? "Close" : "Editor", LevelMapSubEditor.ButtonWidth))
        {
            EditorConditonIndex = EditorConditonIndex == idx ? -1 : idx;
            ResetCommond();
        }
        if (GUILayout.Button("Del", LevelMapSubEditor.ButtonWidth))
        {
            EditorConditonIndex = -1;
            events.m_condition_data_list.RemoveAt(idx);
        }
        GUILayout.Label(LevelMapSubEditor.DataToString(storyCondition.GetType(), storyCondition));
        GUILayout.EndHorizontal();
        if (cyanColor)
        {
            GUI.color = preColor;
        }
    }
    #endregion

    protected override void OnCreate()
    {
        isConditionDownFlag = false;
        if (events == null)
        {
            events = new MainScene.SceneEventData();
            events.eventId = "new";
        }
        else
        {
            if (events.m_condition_data_list.Count > 0)
            {
                isConditionDownFlag = true;
            }
        }
    }
    protected internal override void OnAddConnection(ConnectionPort port, ConnectionPort connection)
    {
        base.OnAddConnection(port, connection);
        Debug.Log(string.Format("{0} 发生链接  port type {3}：port:{1},connection:{2}", GetEventId, (port.body as StoryNode).GetEventId, (connection.body as StoryNode).GetEventId, port.direction));

        //port 是当前自己节点
        if (port.direction == Direction.In) //in 是进入的节点
        {
            var connectionId = (connection.body as StoryNode).GetEventId;

            if (GetEventId == ((port.body as StoryNode).GetEventId))
            {
                bool needAdd = true;
                OnSceneEventConditionData sceneEvt = null;
                for (int i = 0; i < events.m_condition_data_list.Count; i++)
                {
                    var temp = events.m_condition_data_list[i];
                    if (temp.conditionType == EvtConditionType.OnSceneEvt)
                    {
                        sceneEvt = temp as OnSceneEventConditionData;
                        if (sceneEvt.eventId == connectionId)
                        {
                            needAdd = false;
                        }
                    }
                }
                if (needAdd)
                {
                    events.m_condition_data_list.Add(new OnSceneEventConditionData() { eventId = connectionId });
                    isConditionDownFlag = true;
                }
            }
            else
            {
                Debug.LogError("节点链接错误！");
            }
        }
    }
    protected internal override void OnDeleteConnection(ConnectionPort port, ConnectionPort remove)
    {
        base.OnDeleteConnection(port, remove);
        Debug.Log(string.Format("{0} 发生移除  port type {3}：port:{1},connection:{2}", GetEventId, (port.body as StoryNode).GetEventId, (remove.body as StoryNode).GetEventId, port.direction));

        //port 是当前自己节点
        if (port.direction == Direction.In) //in 是进入的节点
        {
            var connectionId = (remove.body as StoryNode).GetEventId;

            if (GetEventId == ((port.body as StoryNode).GetEventId))
            {
                OnSceneEventConditionData sceneEvt = null;
                for (int i = events.m_condition_data_list.Count-1; i >=0; i--)
                {
                    var temp = events.m_condition_data_list[i];
                    if (temp.conditionType == EvtConditionType.OnSceneEvt)
                    {
                        sceneEvt = temp as OnSceneEventConditionData;
                        if (sceneEvt.eventId == connectionId)
                        {
                            events.m_condition_data_list.RemoveAt(i);
                            isConditionDownFlag = true;
                        }
                    }
                }
            }
            else
            {
                Debug.LogError("节点链接错误！");
            }
        }
    }
    public override bool IsBackAvailable()
    {
        return IsAvailable(toPreviousOut);
    }

    public override bool IsNextAvailable()
    {
        return IsAvailable(toNextOUT);
    }
}
